c++ 关于符号 "-"的重载。。(菜鸟求教)

来源:百度知道 编辑:UC知道 时间:2024/06/14 05:55:41
#include<iostream>
using namespace std;

class Person //声明 Person 类
{
friend void operator -(Person p1);
int iApple;
public:
Person(int iApple);
void display();
};

void operator -(Person p1) //声明友元函数(全局的),重载符号 “ - ”!!!
{
p1.iApple= - p1.iApple;
cout<<"-p1.iApple = "<< p1.iApple<<endl; //这里已经是 -5 了,但没反映给 下面的 XiaoWang.iAple
//按理说 既然 函数是 "friend" 声明的,就应该相当于是一个成员函数了
}
int main()
{
Person XiaoWang(5);
cout<<"\n 调用operator -() 前"<<endl;
XiaoWang.display();
operator -(XiaoWang);
cout<<"调用operator -() 后"<<endl;
XiaoWang.display(); //这里XiaoWang.iApple让然是 5 ,为什么不是 “-5”.?????????

}

Person::Person(int iApple)
{
this->iApp

#include<iostream>
using namespace std;

class Person //声明 Person 类
{
friend void operator -(Person& p1); // ----------要传引用哦,否则改变的只是临时对象
int iApple;

public:
Person(int iApple);
void display();
};

// -----------这里也要改
void operator - (Person& p1) //声明友元函数(全局的),重载符号 “ - ”!!!
{
p1.iApple = -p1.iApple;
cout<<"-p1.iApple = "<< p1.iApple <<endl; //这里已经是 -5 了,但没反映给 下面的 XiaoWang.iAple
//按理说 既然 函数是 "friend" 声明的,就应该相当于是一个成员函数了
}

int main()
{
Person XiaoWang(5);
cout<<"\n 调用operator -() 前"<<endl;
XiaoWang.display();
operator -(XiaoWang); // ----------这里直接-XiaoWang就可以了
cout<<"调用operator -() 后"<<endl;
XiaoWang.display(); //这里XiaoWang.iApple让然是 5 ,为什么不是 “-5”.?????????

}

Person::Pers